﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DCT.CodeBox.TaskManager.Codes;
using System.Threading;

namespace DCT.CodeBox.TaskManager
{
    class Program
    {
        static void Main(string[] args)
        {
            QueueTaskDispatcher queueDispatcher = new QueueTaskDispatcher();            
            queueDispatcher.Start();

            ThreadPool.QueueUserWorkItem(delegate {
                List<TaskItemWrapper> items = new List<TaskItemWrapper>();
                for (int i = 0; i < 100; i++)
                {
                    TaskItemWrapper wrapper = new TaskItemWrapper(new ConsoleWriteLineTaskItem(100)
                        , "haha" + i.ToString(), null);
                    items.Add(wrapper);
                }
                queueDispatcher.AddTaskItemRange(items);
            });


            while (true)
            {
                string input = Console.ReadLine();
                input = input.Trim();
                if (input == "x")
                {
                    break;
                }
                else if (input == "p") {
                    queueDispatcher.Pause();
                }
                else if (input == "s")
                {
                    queueDispatcher.Start();
                }
                else if (input == "e") {
                    queueDispatcher.Stop();
                }
                else if (input == "r")
                {
                    queueDispatcher.Resume();
                }
                else
                {
                    queueDispatcher.AddTaskItem(new ConsoleWriteLineTaskItem(), input, null);
                }
            }
        }

        public class ConsoleWriteLineTaskItem : ITaskItem
        {

            private int sleep = 0;

            public ConsoleWriteLineTaskItem()
                : this(0)
            {
            }

            public ConsoleWriteLineTaskItem(int sleep)
            {
                this.sleep = sleep;
            }

            public void Execute(object arg)
            {
                if (this.sleep > 0)
                {
                    Thread.Sleep(this.sleep);
                }
                string text = "[null]";
                if (arg != null)
                {
                    text = arg.ToString();
                }
                Console.WriteLine(DateTime.Now.ToString() + ":" + text);
            }

        }
    }
}
